package com.socialrss.viewlisteners;

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.facebook.Session;
import com.socialrss.R;
import com.socialrss.utils.SocialRssModel;
import com.socialrss.utils.Util;
import com.socialrss.utils.facebook.FacebookUtil;
import com.socialrss.utils.foursquarekit.FoursquareApp;
import com.socialrss.utils.foursquarekit.FoursquareConstants;
import com.socialrss.utils.foursquarekit.FoursquareUtils;
import com.socialrss.utils.twitter.TwitterUtil;
import com.socialrss.accounts.AccountOwner;
import com.socialrss.constants.SocialNetworkNames;
import com.socialrss.constants.SocialNetworkNames.SocialNetKeys;
import com.socialrss.instagramkit.InstagramApp;
import fi.foyt.foursquare.api.FoursquareApi;

public class ConfigureSocialNetwork extends BaseActivity {


	// Login button
	Button btnAdd;
	// Update status button
	Button btnEdit;
	// Logout button
	Button btnRemove;

	Uri uri;
	String username = "";
	Activity act;
	String socialnet;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.settings_social_networks);
		if (getIntent().getExtras() != null) {
			socialnet = getIntent().getExtras().getString("socialnetwork");
		}
		act = ConfigureSocialNetwork.this;

		if (socialnet == null) {
			/**
			 * This if conditions is tested once is redirected from twitter
			 * page. Parse the uri to get oAuth Verifier
			 * */
			uri = getIntent().getData();
			socialnet = "";
			if (uri != null
					&& uri.toString().startsWith(
							TwitterUtil.TWITTER_CALLBACK_URL)) {
				socialnet = SocialNetworkNames.TWITTER;
				if (!TwitterUtil.isTwitterLoggedInAlready()) {
					username = TwitterUtil.setoAuthVerf(uri);
				}
			}
		}
		// initilaize UI elements
		btnAdd = (Button) findViewById(R.id.settingsSN_AddAccountButton);
		btnEdit = (Button) findViewById(R.id.settingsSN_EditAccountButton);
		btnRemove = (Button) findViewById(R.id.settingsSN_RemoveAccountButton);

		/**
		 * Twitter login button click event will call loginToTwitter() function
		 * */
		btnAdd.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// Check if Internet present
				if (!Util.isConnectingToInternet(act)) {
					// Internet Connection is not present
					Util.showAlertDialog(act, "Internet Connection Error",
							"Please connect to working Internet connection",
							false);
					// stop executing code by return
					return;
				}

				if (socialnet.equals(SocialNetworkNames.INSTAGRAM)) {
					instagramAuthentication();
				}
				else if(socialnet.equals(SocialNetworkNames.FOURSQUARE)){
					foursquareAuthenticate();
				}
				else if (socialnet.equals(SocialNetworkNames.TWITTER)) {

					// Check if twitter keys are set
					if (TwitterUtil.isKeysNotSet()) {
						// Internet Connection is not present
						Util.showAlertDialog(act, "Twitter oAuth tokens",
								"Please set your twitter oauth tokens first!",
								false);
						// stop executing code by return
						return;
					}
					// Call login twitter function
					TwitterUtil.loginToTwitter(ConfigureSocialNetwork.this);
				} else if (socialnet.equals(SocialNetworkNames.FACEBOOK)) {
					FacebookUtil.Instance(ConfigureSocialNetwork.this)
							.loginToFacebook();
				}
			}
		});
		/**
		 * Button click event for logout from twitter
		 * */
		btnRemove.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (socialnet.equals(SocialNetworkNames.INSTAGRAM)) {
					removeInstagramAccount();
				} else if (socialnet.equals(SocialNetworkNames.TWITTER)) {
					// Call logout twitter function
					TwitterUtil.logoutFromTwitter();
				} else if (socialnet.equals(SocialNetworkNames.FACEBOOK)) {
					// Call logout twitter function
					FacebookUtil.Instance(ConfigureSocialNetwork.this).logoutFromFacebook();
				}

			}
		});

	}


	/**
	 * Authenticate Foursquare account
	 */
	private void foursquareAuthenticate(){
		AccountOwner owner = SocialRssModel.Instance(null).getAccessTokenOfSocialNet(SocialNetKeys.f_sq.toString());
		if(!owner.isValid()){
			FoursquareApi foursquareApi = new FoursquareApi(FoursquareConstants.CLIENT_ID, FoursquareConstants.CLIENT_SECRET, FoursquareConstants.CALLBACKURL);
			String authenticationUrl = foursquareApi.getAuthenticationUrl();
			FoursquareApp fourApp = new FoursquareApp(this, authenticationUrl);
			fourApp.authorize();
		}
		else{
			showAccountStatusInfo(SocialNetworkNames.FOURSQUARE);
		}
	}
	private void removeInstagramAccount(){
		AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
		builder1.setMessage("Are you sure to remove instagram account? All Instagram connections will be removed, too.")
			.setPositiveButton("OK", new DialogInterface.OnClickListener() {		//ask user if he is sure about this action
				@Override
				public void onClick(DialogInterface dialog, int which) {
					
					SocialRssModel.Instance(getApplicationContext()).removeSocialAccount(SocialNetKeys.ins.toString());
					dialog.dismiss();
				}
			})
			.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			});
		AlertDialog mydial = builder1.create();
		mydial.show();
	}
	protected void onResume() {
		super.onResume();
	}
	/**
	 * Authenticat instagram account
	 * @return
	 */
	private boolean  instagramAuthentication(){
		AccountOwner owner = SocialRssModel.Instance(null).getAccessTokenOfSocialNet(SocialNetKeys.ins.toString());
		if(!owner.isValid()){
			InstagramApp instlog = new InstagramApp(this);
			instlog.authorize();
		}
		else{
			showAccountStatusInfo(SocialNetworkNames.INSTAGRAM);
		}
		return true;
	}
	private void showAccountStatusInfo(String accountname){
		AlertDialog.Builder builder1 = new AlertDialog.Builder(getApplicationContext());
		builder1.setMessage(accountname + " account has been already authenticated.")
			.setPositiveButton("OK", new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			});
		AlertDialog mydial = builder1.create();
		mydial.show();
	}


	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Session.getActiveSession().onActivityResult(this, requestCode,
				resultCode, data);
	}

}
